package gw.com.android.ui.onlive.analyst;

import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gwtsz.gts2.hx.R;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import gw.com.android.app.AppMain;
import gw.com.android.ui.PraiseAndTransmitAdapter;
import gw.com.android.ui.onlive.DiscussData;
import gw.com.android.ui.views.ExpandableTextView;
import gw.com.android.ui.views.ImageWatcher;
import gw.com.android.utils.CopyShowerUtil;
import gw.com.android.utils.ImageLayoutHelper;
import www.com.library.util.StringFormatter;

public class AnalystPostAdapter extends PraiseAndTransmitAdapter {

    /**
     * 左边菜单栏适配器数据对象
     */
    private Context mContext;
    private LayoutInflater mInflater;
    private ImageWatcher watcher;
    private List<DiscussData> mDatas;

    public AnalystPostAdapter(Activity mActivity) {
        super(mActivity);
        mInflater = mActivity.getLayoutInflater();
        mContext = mActivity;
    }

    public void setWatcher(ImageWatcher watcher) {
        this.watcher = watcher;
    }

    /**
     * 上拉刷新替换新数据
     */
    public void setData(List<DiscussData> list) {
        mDatas = list;
        notifyDataSetChanged();
    }

    /**
     * 下拉刷新追加数据
     */
    public void addData(List<DiscussData> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        if (mDatas == null) {
            mDatas = list;
        } else {
            mDatas.addAll(list);
        }
        notifyDataSetChanged();
    }

    /**
     * 根据position返回界面item数据对象
     */
    public DiscussData getItem(int position) {
        if (mDatas != null) {
            if (position >= 0 && position < mDatas.size()) {
                return mDatas.get(position);
            }
        }
        return null;
    }


    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(mContext).inflate(R.layout.list_item_analyst_post, parent, false);
        return new MyHolder(v);
    }


    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        MyHolder mHolder = (MyHolder) holder;
        DiscussData mItem = getItem(position);
        //把时间字符串格式化
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
        df.setTimeZone(TimeZone.getTimeZone("GMT+0"));
        if (null != mItem) {
            try {
                Date date = df.parse(mItem.showDate);
                mHolder.tv_time.setText(StringFormatter.instance().toDateTimeHM(date));
            } catch (ParseException e) {
                e.printStackTrace();
            }

            //区分是不是精华帖
            int best = mItem.best;
            if (best == 1) {
                mHolder.tv_best.setVisibility(View.VISIBLE);
            } else {
                mHolder.tv_best.setVisibility(View.GONE);
            }

            // 获得分享数
            dealCount(mHolder.tv_transmit_count, mItem.transmit);
            initTransmitLayout(mItem.id, mItem.transmit, mHolder.tv_transmit_count);//这里，加载缓存中的分享数
            ShareClickListener lis = new ShareClickListener(mItem.id, mItem.remark, mHolder.tv_transmit_count, mItem.transmit, EVENT_FROM_ANALYST);
            mHolder.ll_transmit.setOnClickListener(lis);//給这两个组件的父容器设置点击事件
            // 点赞数
            dealCount(mHolder.mPraiseBtn, mItem.praise);
            mHolder.discuss_like_container.setOnClickListener(new PraiseLis(mItem, mHolder.discuss_like_effect, mHolder.mPraiseBtn, mHolder.discuss_like));
            initPraiseLayout(mItem.id, mHolder.discuss_like, mHolder.mPraiseBtn);

            //区分是不是置顶帖
            int sorted = mItem.sorted;
            if (sorted == 1) {
                mHolder.tv_sort_1.setVisibility(View.VISIBLE);
            } else {
                mHolder.tv_sort_1.setVisibility(View.GONE);
            }

            mHolder.mContentview.setConvertText(true, mItem.remark);
            new CopyShowerUtil(mContext, mHolder.expandable_text);
            //帖子图片
            String s = mItem.tradeImgs;
            if (TextUtils.isEmpty(s)) {//为了兼容旧数据，必须这么做（因为旧的数据并没有tradeImgs这个字段，所以必须手动造）
                String tradeImg = mItem.tradeImg;
                s = "[\"" + tradeImg + "\"]";
            }
            final List<ImageView> images = new ArrayList<>();
            final List<String> urlList = new ArrayList<>();
            mHolder.ll_trade_image.removeAllViews();
            mHolder.ll_trade_image_for_only_one.removeAllViews();
            if (!TextUtils.isEmpty(s)) {
                Type type = new TypeToken<ArrayList<String>>() {
                }.getType();
                List<String> shaidanImageList = new Gson().fromJson(s, type);//GSON解析数组的方式也是很诡异，和Fastjson完全不同
                if (shaidanImageList.size() == 1) {//如果不包含中括号，就是只有一张图
                    mHolder.ll_trade_image.setVisibility(View.GONE);
                    mHolder.ll_trade_image_for_only_one.setVisibility(View.VISIBLE);
                    ImageLayoutHelper.getInstance(watcher).setSizeofSingleImg(mContext, mItem.imgSize);
                    ImageLayoutHelper.getInstance(watcher).addImageIntoLayout(mContext, 0, mHolder.ll_trade_image_for_only_one, shaidanImageList.get(0), images, urlList, true);

                } else {//否则就是多张图的情况，要进行JSON解析 ，json大概是这样的["1.png","2.png"]
                    mHolder.ll_trade_image.setVisibility(View.VISIBLE);
                    mHolder.ll_trade_image_for_only_one.setVisibility(View.GONE);

                    for (int i = 0; i < shaidanImageList.size(); i++) {//轮流创建imageView并且加载到布局中
                        ImageLayoutHelper.getInstance(watcher).addImageIntoLayout(mContext, i, mHolder.ll_trade_image, shaidanImageList.get(i), images, urlList, false);
                    }
                }
            }

            //处理分割线
            if (position + 1 == getItemCount()) {// 如果是最后一项，就隐藏分割线
                mHolder.ll_sep.setVisibility(View.GONE);
            } else {
                mHolder.ll_sep.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public int getItemCount() {
        if (mDatas == null) return 0;
        return mDatas.size();
    }

    class MyHolder extends RecyclerView.ViewHolder {

        TextView tv_time;
        ExpandableTextView mContentview;
        TextView expandable_text;
        LinearLayout ll_trade_image_for_only_one;
        LinearLayout ll_trade_image;
        TextView tv_best;
        TextView tv_transmit_count;
        TextView tv_sort_1;
        TextView mPraiseBtn;
        LinearLayout ll_sep;
        LinearLayout ll_transmit;
        LinearLayout discuss_like_container;
        ImageView discuss_like_effect;
        ImageView discuss_like;

        public MyHolder(View itemView) {
            super(itemView);
            tv_time = (TextView) itemView.findViewById(R.id.tv_time);
            mContentview = (ExpandableTextView) itemView.findViewById(R.id.tv_news_content);
            mContentview.setExpandCollapseHintText(AppMain.getAppString(R.string.expandable_expand), AppMain.getAppString(R.string.expandable_collapse));
            ll_trade_image = (LinearLayout) itemView.findViewById(R.id.ll_trade_image);
            ll_trade_image_for_only_one = (LinearLayout) itemView.findViewById(R.id.ll_trade_image_for_only_one);
            tv_best = (TextView) itemView.findViewById(R.id.tv_best);
            tv_transmit_count = (TextView) itemView.findViewById(R.id.tv_transmit_count);
            tv_sort_1 = (TextView) itemView.findViewById(R.id.tv_sort_1);
            mPraiseBtn = (TextView) itemView.findViewById(R.id.praise_button);
            expandable_text = (TextView) itemView.findViewById(R.id.expandable_text);
            ll_sep = (LinearLayout) itemView.findViewById(R.id.ll_sep);
            ll_transmit = (LinearLayout) itemView.findViewById(R.id.ll_transmit);
            discuss_like_container = (LinearLayout) itemView.findViewById(R.id.discuss_like_container);
            discuss_like_effect = (ImageView) itemView.findViewById(R.id.discuss_like_effect);
            discuss_like = (ImageView) itemView.findViewById(R.id.discuss_like);
        }
    }
}
